<template>
  <div class="box">
    <div class="chart">
      <div id="charts" ref="chart">
        <!-- PDF.js will render the PDF here -->
      </div>
    </div>
  </div>
</template>

<script>
import { onMounted, ref } from "vue";
import * as pdfjsLib from "pdfjs-dist/webpack";

export default {
  name: "Overview",
  mounted() {
    this.$emit("changeTimeIndex", 18);
    this.$emit("changeIsSelect2", true);
    this.$emit("changeIsSelect3", false);
    this.$emit("changeIsTimeOperator", false);
  },
  setup() {
    const chart = ref(null);

    onMounted(() => {
      const url = "/Overview.pdf";
      
      const loadingTask = pdfjsLib.getDocument(url);
      loadingTask.promise.then(pdf => {
        console.log("PDF loaded");

        const renderPage = (pageNum) => {
          pdf.getPage(pageNum).then(page => {
            console.log(`Page ${pageNum} loaded`);

            // Calculate the scale to fit the chart container width
            const containerWidth = chart.value.clientWidth;
            const viewport = page.getViewport({ scale: 1 });
            const scale = containerWidth / viewport.width;

            const scaledViewport = page.getViewport({ scale });

            // Prepare canvas using PDF page dimensions
            const canvas = document.createElement("canvas");
            const context = canvas.getContext("2d");
            canvas.height = scaledViewport.height;
            canvas.width = scaledViewport.width;

            // Append canvas to the chart div
            chart.value.appendChild(canvas);

            // Render PDF page into canvas context
            const renderContext = {
              canvasContext: context,
              viewport: scaledViewport,
            };
            const renderTask = page.render(renderContext);
            renderTask.promise.then(() => {
              console.log(`Page ${pageNum} rendered`);
              if (pageNum < pdf.numPages) {
                renderPage(pageNum + 1);
              }
            });
          });
        };

        // Start rendering from the first page
        renderPage(1);
      }).catch(reason => {
        // PDF loading error
        console.error(reason);
      });
    });

    return {
      chart,
    };
  }
};
</script>

<style scoped lang="scss">
@media screen and (min-width: 700px) {
  .box {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .chart {
    border: 3px double #1996ef;
    background-color: #fff;
    margin: 60px;
    width: 60%;
    height: auto;
    position: relative;

    #charts {
      width: 100%;
      height: 70vh;
      overflow-y: auto;
    }
  }
}
</style>
